const fs = require("fs");
const path = require("path");
const prettier = require("prettier");
const t = require("../config/dict");
const { cpDir, log } = require("./utils");

module.exports = (context, filter) => {
  const metaData = context.metadata;
  const dirName = metaData.projectDir;
  const filePath = path.resolve(process.cwd(), path.join(".", dirName));
  const localPath = path.resolve(__dirname, "../template/");
  const projectClient = context.metadata.projectClient.toLowerCase();
  const projectType = context.metadata.projectType[0].toLowerCase();
  const stack = metaData.projectTechnologyStack.toLowerCase();
  const isVite = /vite/.test(projectType);
  let activeFile = filePath + (isVite ? "/" : "/public/") + "index.html";
  activeFile = fs.existsSync(activeFile)
    ? activeFile
    : isVite
    ? filePath + "/public/index.html"
    : filePath + "/index.html";
  const { keywords, description, author, copyright, title, mobileOps } = {
    keywords: metaData.projectKeywords,
    description: metaData.projectDescription,
    author: metaData.projectAuthor,
    copyright: metaData.projectAuthor,
    title: metaData.projectName,
    ...{
      mobileOps: {
        title: metaData.projectName,
        appid: metaData.projectAppId,
        touchIcon: {
          57: "",
          114: "",
          72: "",
          144: "",
        },
        touchStart: {
          landscape: "",
          portrait: "",
          default: "",
        },
        format: {
          telephone: "no",
          email: "no",
          address: "no",
        },
      },
    },
  };

  const webpackHead = {
    vue: `
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title><%= htmlWebpackPlugin.options.title %></title>
  `,
    react: `
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <title>React App</title>
  `,
  };
  const viteHead = `
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <title>Vite App</title>
  `;

  const baseMode = `
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="keywords" content="${keywords}">
    <meta name="description" content="${description}">
    <meta name="author" content="${author}">
    <meta name="copyright" content="${copyright}">
    <meta name="robots" content="index, follow">
    <meta name="renderer" content="webkit"/>
    <meta name="nightmode" content="disable">
    <meta name="HandheldFriendly" content="true">

    <meta property="og:title" content="${title}">
    <meta property="og:description" content="${description}">

    <meta name="revisit-after" content="5 days">

    <meta http-equiv="page-enter" content="blendTrans(duration=5)">

    <meta http-equiv="cache-control" content="no-transform">
    <meta http-equiv="cache-control" content="no-siteapp">
    `;

  const fixHtml5 = `<!--[if lt IE 9]>
    <script src="lib/js/html5shim.min.js"></script>
    <script src="lib/js/respond.min.js"></script>
    <![endif]-->`;

  const noCache = `
    <!-- no-cache -->
    <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="expires" content="0">
    `;

  const mobileMode = `
    <!-- QQ -->
    <meta name="x5-orientation" content="portrait">
    <meta name="x5-fullscreen" content="true">
    <meta name="x5-page-mode" content="app">
    <!-- UC -->
    <meta name="screen-orientation" content="portrait">
    <meta name="full-screen" content="yes">
    <meta name="browsermode" content="application">

    <meta name="google" value="notranslate">

    <!-- ios -->
    <meta name="apple-mobile-web-app-capable" content="no">
    <meta name="apple-mobile-web-app-title" content="${mobileOps.title}">
    <meta name="apple-itunes-app" content="${mobileOps.appid}">

    <link rel="apple-touch-icon" sizes="57x57" href="${mobileOps.touchIcon["57"]}">
    <link rel="apple-touch-icon" sizes="114x114" href="${mobileOps.touchIcon["114"]}">
    <link rel="apple-touch-icon" sizes="72x72" href="${mobileOps.touchIcon["72"]}">
    <link rel="apple-touch-icon" sizes="144x144" href="${mobileOps.touchIcon["144"]}">

    <link rel="apple-touch-startup-image" href="${mobileOps.touchStart.landscape}"  media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)">
    <link rel="apple-touch-startup-image" href="${mobileOps.touchStart.portrait}" media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)">
    <link rel="apple-touch-startup-image" href="${mobileOps.touchStart.default}">

    <!-- mobile -->
    <meta name="format-detection" content="telephone=${mobileOps.format.telephone}">
    <meta name="format-detection" content="email=${mobileOps.format.email}">
    <meta name="format-detection" content="address=${mobileOps.format.address}">
    `;

  const upDateFile = () => {
    let data = fs.readFileSync(activeFile, "utf-8");
    data = data
      .replace(/\n|\r/gim, "")
      .replace(/\s{2,}/gim, " ")
      .replace(/<head>(.+)<\/head>/gim, (a, b) => {
        a = a.replace(
          b,
          [
            isVite ? viteHead : webpackHead[stack] || webpackHead["vue"],
            baseMode,
            fixHtml5,
            noCache,
            mobileMode,
          ].join("")
        );
        return a;
      });
    fs.writeFileSync(
      activeFile,
      prettier.format(data, {
        semi: false,
        parser: "html",
      })
    );
    cpDir(localPath + "/js", filePath + "/src/lib/js");
    log("success", {
      message: [
        t(context.lang, "更新"),
        "index.html",
        t(context.lang, "完成"),
        t(context.lang, "。"),
      ].join(" "),
    });
  };

  if (projectClient === "web" && /vue|react/.test(stack)) {
    if (activeFile && fs.existsSync(activeFile)) {
      /* if (metaData.projectMode === "manual") {
        return inquirer
          .prompt([
            {
              name: "projectHTMLMeta",
              message: t(context.lang, "更新") + " HTML META" + "?",
              default: "yes",
              pageSize: 3,
              type: "rawlist",
              choices: [...t(context.lang, boolChoies)],
            },
          ])
          .then((answers) => {
            let bool = answers.projectHTMLMeta;
            if (bool === "yes") {
              upDateFile();
            } else {
              log("error", {
                message: [
                  t(context.lang, "更新"),
                  "index.html",
                  t(context.lang, "失败"),
                  t(context.lang, "。"),
                ].join(" "),
              });
            }
            return context;
          });
      } else { */
      upDateFile();
      return context;
      //}
    } else {
      log("error", {
        message: [
          t(context.lang, "更新"),
          "index.html",
          t(context.lang, "失败"),
          t(context.lang, "。"),
        ].join(" "),
      });
      return context;
    }
  } else {
    log("warn", {
      message: [
        t(context.lang, "跳过"),
        "HTML META",
        t(context.lang, "。"),
      ].join(" "),
    });
    return context;
  }
};
